var hs_utils = {

    loginView: "login.html",

    init: function () {
        $.ajaxSetup({
            xhrFields: {
                withCredentials: true
            }
        })
    },

    getViewUrl: function (url) {
        return "http://localhost:63342/hzsparrow-business-base-view/" + url;
    },

    getServerUrl: function (url) {
        return "http://localhost:8082/" + url;
    },

    post: function (url, postData, cbsuccess, cberror, isJson = false) {
        let contentType_ = "application/x-www-form-urlencoded";
        let url_ = hs_utils.getServerUrl(url);
        let data_ = postData;
        if (isJson) {
            contentType_ = "application/json";
            data_ = JSON.stringify(postData);
        }
        $.ajax(url_, {
            type: "POST",
            data: data_,
            dataType: "json",
            xhrFields: {
                withCredentials: true
            },
            contentType: contentType_,
            success: function (data) {
                if ((!data.success) && data.code == 401) {
                    window.location.href = hs_utils.getViewUrl(hs_utils.loginView);
                    return;
                }
                if (cbsuccess) {
                    cbsuccess(data);
                } else {
                    if (!data.success) {
                        layui.layer.msg(data.msg);
                    }
                }
            },
            error: function (data) {
                if (cberror) {
                    cberror(data);
                } else {
                    layui.layer.msg(data);
                }

            }
        })
    },

    postDownload: function (url, postData, cbsuccess, cberror, isJson = false) {
        let xhr = new XMLHttpRequest();
        let url_ = hs_utils.getServerUrl(url);
        xhr.open('POST', url_, true);
        let contentType_ = "application/x-www-form-urlencoded";
        let data_ = postData;
        if (isJson) {
            contentType_ = "application/json";
            data_ = JSON.stringify(postData);
        }
        xhr.setRequestHeader("Content-Type", contentType_);
        xhr.responseType = 'blob';
        xhr.withCredentials = true;
        xhr.onload = function (res) {
            if (this.status === 200) {
                var type = xhr.getResponseHeader('Content-Type');
                var filename = xhr.getResponseHeader('Content-Disposition').split("=")[1].replace(/"/g, "");
                var blob = new Blob([this.response], {type: type});
                if (typeof window.navigator.msSaveBlob !== 'undefined') {
                    /*
                     * For IE
                     * >=IE10
                     */
                    window.navigator.msSaveBlob(blob, filename);
                } else {
                    /*
                     * For Non-IE (chrome, firefox)
                     */
                    var URL = window.URL || window.webkitURL;
                    var objectUrl = URL.createObjectURL(blob);
                    if (filename) {
                        var a = document.createElement('a');
                        if (typeof a.download === 'undefined') {
                            window.location = objectUrl;
                        } else {
                            a.href = objectUrl;
                            a.download = filename;
                            document.body.appendChild(a);
                            a.click();
                            a.remove();
                        }
                    } else {
                        window.location = objectUrl;
                    }
                }
            }
        }
        xhr.send(data_);
    },

    get: function (url, getData, cbsuccess, cberror) {
        let contentType_ = "application/x-www-form-urlencoded";
        let url_ = hs_utils.getServerUrl(url);
        let data_ = getData;
        $.ajax(url_, {
            type: "GET",
            data: data_,
            dataType: "json",
            xhrFields: {
                withCredentials: true
            },
            contentType: contentType_,
            success: function (data) {
                if (cbsuccess) {
                    cbsuccess(data);
                } else {
                    if (!data.success) {
                        layui.layer.msg(data.msg);
                    }
                }
            },
            error: function (data) {
                if (cberror) {
                    cberror(data);
                } else {
                    layui.layer.msg(data);
                }

            }
        })
    },

    getView: function (url, getData, cbsuccess, cberror) {
        let contentType_ = "application/x-www-form-urlencoded";
        let url_ = hs_utils.getViewUrl(url);
        let data_ = getData;
        $.ajax(url_, {
            type: "GET",
            data: data_,
            xhrFields: {
                withCredentials: true
            },
            contentType: contentType_,
            success: function (data) {
                if (cbsuccess) {
                    cbsuccess(data);
                } else {
                    layui.layer.msg(data);
                }
            },
            error: function (data) {
                if (cberror) {
                    cberror(data);
                } else {
                    layui.layer.msg(data);
                }

            }
        })
    },

    /**
     * 渲染分页表格
     *
     * @param config {elem: 表格的id, url: 数据接口, toolbar: 左侧操作按钮（可为空，默认使用新增按钮）,cols: 表头}
     * @param eventConfig {filter: 表格的filter, toolbar: 左侧按钮的事件[{name: 事件名, handler: 事件函数(自动传入当前行数据信息)}], tool: 表格内操作按钮事件[{name: 事件名, handler:事件函数}],other: 其他事件[{name: 事件名, handler:事件函数}] }
     * @returns {*}
     */
    renderPageTable: function (config, eventConfig) {
        let table = layui.table;
        let tableConfig = hs_utils.getDefaultTableConfig();
        for (var param in config) {
            if (param == 'url') {
                config[param] = hs_utils.getServerUrl(config[param]);
            }
            tableConfig[param] = config[param];
        }
        if (!tableConfig.method) {
            tableConfig.method = 'post';
        }
        let pageTable = table.render(tableConfig);
        if (eventConfig && eventConfig.filter) {
            if (eventConfig.toolbar) {
                table.on('toolbar(' + eventConfig.filter + ')', function (obj) {
                    let layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
                    for (let index in eventConfig.toolbar) {
                        let event = eventConfig.toolbar[index];
                        if (layEvent === event.name) {
                            event.handler(obj);
                        }
                    }
                });
            }
            if (eventConfig.tool) {
                table.on('tool(' + eventConfig.filter + ')', function (obj) {
                    let data = obj.data; //获得当前行数据
                    let layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
                    for (let index in eventConfig.tool) {
                        let event = eventConfig.tool[index];
                        if (layEvent === event.name) {
                            event.handler(obj);
                        }
                    }
                });
            }
            if (eventConfig.other) {
                for (let index in eventConfig.other) {
                    let event = eventConfig.other[index];
                    table.on(event.name + "(" + eventConfig.filter + ')', function (obj) {
                        event.handler(obj);
                    });
                }
            }
        }
        return pageTable;
    },

    getDefaultTableConfig: function () {
        let tableConfig = {
            height: 430,
            page: true, //开启分页
            toolbar: '#tableToolBar',
            defaultToolbar: ['filter', 'exports'],
            parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.data //解析数据列表
                }
            },
            request: {
                pageName: 'page', //页码的参数名称，默认：page
                limitName: 'size' //每页数据量的参数名，默认：limit
            },
            response: {
                statusCode: 200 //规定成功的状态码，默认：0
            }
        };
        return tableConfig;
    },

    /**
     * 渲染从字典中获取数据的选择框
     *
     * @param elementId select组件ID
     * @param formFilter 所在form表单的lay-filter
     * @param typeId 字典类型ID
     * @param valueField 选择框的真实值对应的字典字段，默认intValue,可选strValue
     */
    renderDictionarySelect: function (elementId, formFilter, typeId, valueField = "intValue") {
        hs_utils.post("/hzs/dictionarydetail/findByHsdtId", {hsdtId: typeId}, function (data) {
            let data_ = data.data;
            if (data_) {
                let html = '<option value="">请选择</option>';
                for (let index in data_) {
                    let option = data_[index];
                    html += '<option value="' + option[valueField] + '">' + option.hsddName + '</option>';
                }
                $('#' + elementId).html(html);
                layui.form.render('select', 'formFilter');
            }
        })
    },

    /**
     * 合并where条件，防止where条件残留
     * @param whereData
     * @param newWhere
     */
    mergeWhereData: function (whereData, newWhere) {
        if (!whereData) {
            whereData = {};
        }
        if (!newWhere) {
            newWhere = {};
        }
        for (let param in whereData) {
            if (!newWhere[param]) {
                whereData[param] = null;
            }
        }
        for (let param in newWhere) {
            whereData[param] = newWhere[param];
        }
        return whereData;
    }
}
hs_utils.init();